<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>支付</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" type="text/css" href="../default/css/mui.min.css"/>
    <link rel="stylesheet" type="text/css" href="../default/css/index.css"/>
    <style>
        body {
            background: #f2f2f2;
        }

        header a {
            color: #fff;
        }

        .mui-bar .mui-title {
            color: #fff;
        }

        .mui-content {
            background: #f2f2f2;
        }

        .mui-bar-nav ~ .mui-content {
            padding-bottom: 50px;
        }

        .mui-bar-transparent {
            background: rgba(255, 219, 40, 0);
        }

        .mui-content {
            padding-bottom: 50px;
        }

        /*样式覆盖*/
        .task-maseg {
            text-align: center;
            margin: 80px auto;
        }

        /*重写样式-美化*/
        .mui-input-row label {
            font-size: 14px;
        }
        #yuedub{
            display: none;
        }
    </style>
</head>
<body>
<header class="mui-bar mui-bar-transparent">
    <a class="mui-icon mui-icon-left-nav mui-pull-left back-tohost"></a>
    <h1 class="mui-title">支付</h1>
</header>

<div class="mui-content">
    <div class="order-type-tit-box">
        <div class="mui-row">
            <div class="mui-col-sm-6 mui-col-xs-6">
                <div class="task-maseg">
                    <h3 id="commission">--</h3>
                    <p>佣金</p>
                </div>
            </div>
            <div class="mui-col-sm-6 mui-col-xs-6">
                <div class="task-maseg">
                    <h3 id="balance">--</h3>
                    <p>阅读宝</p>
                </div>
            </div>
        </div>
    </div>
    <!--<div class="top-shadow"></div>-->
    <div class="mui-card pading10-15 border-radius15">
        <b>商品名称:<b class="red" id="tradeName"></b></b><br>
        <b>支付金额:￥ <b class="red" id="purchaseAmount"></b></b><br>
        <b>阅读宝数量: <b class="red" id="commodityReadingTreasure"></b></b>

    </div>
    <div class="mui-card pading10-15 border-radius15">
        <h5>请选择付款方式</h5>
        <div class="mui-input-row mui-radio" id="weix">
            <label>微信支付</label>
            <input name="radio1" type="radio" id="wecathbuy" value="1" checked>
        </div>
        <div class="mui-input-row mui-radio">
            <label>余额支付</label>
            <input name="radio1" type="radio" id="commissionbuy"  value="2">
        </div>
        <div class="mui-input-row mui-radio" id="yuedub">
            <label>阅读宝支付</label>
            <input name="radio1" type="radio" id="balancebuy" value="3" disabled="disabled">
        </div>
    </div>
    <div class="pading10-15">
        <button type="button" class="mui-btn mui-btn-warning cash-withdrawal-btn subm-this-order">立即支付</button>
    </div>


</div>


<script src="../default/js/jquery-2.14.js" type="text/javascript" charset="utf-8"></script>
<script src="../default/js/mui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../default/js/cookie.js"></script>
<script src="../default/js/code.js" type="text/javascript" charset="utf-8"></script>
<script src="../default/js/index.js" type="text/javascript" charset="utf-8"></script>
<script src="../default/js/public.js"></script>
<script type="text/javascript" src="../default/js/vconsole.js"></script>

<script type="text/javascript" src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<!--搜狐的获取手机IP接口-->
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>

<script>
    mui.init();

    // ajax地址

    mui('header').on('tap', '.back-tohost', function (e) {
        e.preventDefault();
        mui.openWindow({
            url: 'orderStatus.html',
        });
    });


    $(function () {
        OrderController();
        uservipen();
        findByUserBalance();
        // submthisorder();
        userPaymen();

    });

    var userId='1169';

    // 订单金额
    var totalPrice = 1.00;
    // 订单id
    var orderId = '931';
    // 订单状态
    var orderStatus = '未付款';
    var orderNumber = '201908030915450';
    // 用户会员状态
    var uservip = '';
    // 阅读宝余额
    var balance = '';
    // 分销佣金余额
    var commission = '';

    var tradeName = localStorage.getItem('tradeName');

    var commodityReadingTreasure = localStorage.getItem('commodityReadingTreasure');

    function OrderController() {
        //商品名字

        $("#tradeName").html(tradeName);
        //订单金额

        $("#purchaseAmount").html(totalPrice);
        // 获取商品的阅读宝金额

        $("#commodityReadingTreasure").html(commodityReadingTreasure);

        if(totalPrice == 0 || totalPrice == '' || totalPrice == null){
            $("#wecathbuy").attr('checked',false);
            $("#wecathbuy").attr('disabled',true);
            $("#weix").hide();
            $("#balancebuy").attr('disabled',false);
            $("#balancebuy").attr('checked',true);
            $("#yuedub").show();
        }


    };

    function uservipen() {
        // 判断用户是否为会员
        $.ajax({
            url: website + '/UserController/areMembers',
            type: 'post',
            data: {
                userId: userId
            },
            success: function (data) {
                console.log(data);
                uservip = data.data
            }
        });
    }


    // 查询用户的分销佣金和阅读宝,和朋友
    function findByUserBalance() {
        // 查询用户的阅读宝和余额
        mui.showLoading("正在加载..", "div");

        $.ajax({
            url: website + '/UserController/findByUserBalance ',
            type: 'post',
            data: {userId: userId},
            success: function (data) {
                $("#balance").html(data.data.balance);
                balance = data.data.balance;
                $("#commission").html(data.data.commission);
                commission = data.data.commission;
                // userPaymen(balance,commission);
                mui.hideLoading();
            },
            error: function () {
                mui.showLoading("未知错误..", "div");
            }
        });

    };


    //获得手机终端ip
    var mobileIP = returnCitySN.cip;

    var timeStamp, nonceStr, package, paySign;

    // 支付
    function userPaymen() {
        //商品是否为vip产品
        var designatedProduct = localStorage.getItem('designatedProduct');
        // 获取商品的阅读宝金额
        var commodityReadingTreasure = localStorage.getItem('commodityReadingTreasure');
        //订单金额
        var purchaseAmount = localStorage.getItem('purchaseAmount');




        if (uservip == '是' && designatedProduct == '是') {
            mui.alert('VIP用户不可继续购买VIP产品', '提示', function () {
                mui.openWindow({
                    url: 'orderStatus.html',
                });
            });
            return;
        } else {

            mui(".pading10-15").on('tap', '.subm-this-order', function () {

                var paymentMethod = $('input:radio:checked').val();
                console.log(paymentMethod);
                var orderStatus = '未付款';
                if (orderStatus != "未付款") {
                    mui.alert('该订单已经过期', '提示', function () {
                        mui.openWindow({
                            url: 'orderStatus.html',
                        });
                    });
                    return false;
                }else if(paymentMethod == '2'){
                    mui.showLoading("正在加载..", "div");
                    $.ajax({
                        url: website + '/OrderController/userPayment',
                        type: 'post',
                        dataType: "json",
                        data: {
                            orderNumber: orderNumber,
                            paymentMethod: paymentMethod
                        },
                        success: function (data) {
                            mui.hideLoading();
                            mui.alert('支付成功', '提示', function () {
                                mui.showLoading("正在加载..", "div");
                                setTimeout(function () {
                                    mui.hideLoading();
                                    mui.openWindow({
                                        url: 'orderStatus.html',
                                    });
                                }, 500);
                            });
                        },
                    });
                    return;
                } else if (paymentMethod == '1') {
                    mui.showLoading("正在加载..", "div");
                    var orderId1 = '';
                    /**订单号*/
                    var orderNumber1 = '';
                    /**订单总价钱*/
                    var totalPrice1 = 1;

                    var param = "code";
                    var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
                    var r = window.location.search.substr(1).match(reg); //匹配目标参数
                    var code = r[2];
                    $.ajax({
                        url: website+'/WxPayController/pay/',
                        type: 'POST',
                        dataType: 'json',
                        //url需要编码传入而且要是完整的url除#之后的
                        data: {
                            "url": encodeURIComponent(window.location.href.split("#")[0]),
                            "code": code,
                            "totalPrice": totalPrice1,
                            "orderNumber": orderNumber,
                            "mobileIP": mobileIP
                        },
                        success: function (res) {
                            mui.hideLoading();
                            timeStamp = res.timestamp;
                            nonceStr = res.nonceStr;
                            package = res.prepay_id;
                            paySign = res.paySign;


                            wx.config({
                                debug: true, //调试阶段建议开启
                                appId: "wxed752d87990909bb",//APPID
                                timestamp: res.timestamp,//上面main方法中拿到的时间戳timestamp
                                nonceStr: res.nonceStr,//上面main方法中拿到的随机数nonceStr
                                signature: res.signature,//上面main方法中拿到的签名signature
                                //需要调用的方法接口
                                jsApiList: [
                                    'chooseWXPay'
                                ]
                            });

                            wx.ready(function () {
                                wx.chooseWXPay({
                                    timestamp: res.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                                    nonceStr: res.nonceStr, // 支付签名随机串，不长于 32 位
                                    package: res.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                                    signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                                    paySign: res.paySign, // 支付签名
                                    success: function (res) {
                                        if (res.errMsg == "chooseWXPay:ok") {
                                            window.top.location.replace(window.location.href);
                                            window.location.href = "myOrder-list.html";
                                        } else {
                                            window.top.location.replace(window.location.href);
                                            window.location.href = "myOrder-list.html";
                                        }
                                    },
                                    cancel: function (res) {
                                        window.top.location.replace(window.location.href);
                                        window.location.href = "myOrder-list.html";
                                    }
                                });
                            });

                            if (typeof WeixinJSBridge == "undefined") {
                                // window.top.location.replace(window.location.href);
                                if (document.addEventListener) {
                                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                } else if (document.attachEvent) {
                                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                }
                            } else {
                                onBridgeReady();
                            }
                        }
                    })
                    return false;
                } else if (designatedProduct == '是' && paymentMethod == '3') {
                    mui.alert('此商品不可用阅读宝购买', '提示', function () {
                    });
                    return false;
                } /*else if (paymentMethod == 2 && commission < purchaseAmount) {
                    mui.alert('您的分销佣金余额不足');
                    return false;
                }*/ else if (paymentMethod == 3 && balance < purchaseAmount) {
                    mui.alert('您的阅读宝余额不足');
                    return false;
                } else {
                    mui.showLoading("正在加载..", "div");
                    $.ajax({
                        url: website + '/OrderController/userPayment',
                        type: 'post',
                        dataType: "json",
                        data: {
                            orderNumber: orderNumber,
                            paymentMethod: paymentMethod
                        },
                        success: function (data) {
                            /*if(data.code==400){
                                mui.alert(data.msg, '提示', function () {
                                    setTimeout(function () {
                                        mui.openWindow({
                                            url: 'orderStatus.html',
                                        });
                                    }, 500);
                                });
                            }
                            if(data.code==200){

                            }*/
                            mui.hideLoading();
                            mui.alert('支付成功', '提示', function () {
                                mui.showLoading("正在加载..", "div");
                                setTimeout(function () {
                                    mui.hideLoading();
                                    mui.openWindow({
                                        url: 'orderStatus.html',
                                    });
                                }, 500);
                            });
                        },
                    });
                }
            });
        }

    };

    function onBridgeReady() {
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId": "wxed752d87990909bb",     //公众号名称，由商户传入
                "timeStamp": timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr": nonceStr, //随机串
                "package": package,
                "signType": "MD5",         //微信签名方式：
                "paySign": paySign //微信签名
            },
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // message: "微信支付成功!",
                    window.location.href = "myOrder-list.html";
//                                window.location.replace("@Url.Content("~/WxPay/Success?ordercode=@(Model.order_no)"));
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    window.location.href = "myOrder-list.html";
                    // message: "已取消微信支付!"
                }
            });
    }

    function submthisorder() {
        if (orderId == null) {
            mui.alert('请选择你需要支付的订单', '提示', function () {
                mui.showLoading("正在加载..", "div");
                setTimeout(function () {
                    mui.hideLoading();
                    mui.openWindow({
                        url: 'myOrder-list.html',
                    });
                }, 500);
            });
        }
        ;

    }


    $(function () {
        pushHistory();
        window.addEventListener("popstate", function (e) {
            window.location.href = "orderStatus.html";
        }, false);

        function pushHistory() {
            var state = {
                title: "title",
                url: "#"
            };
            window.history.pushState(state, "title", "#");
        }
    });


</script>
</body>
</html>